﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevEx.Thanh.UserControl;
using DevEx.Thanh.reports;
using DevExpress.XtraEditors;
using System.Xml;
using System.Data.Linq;
using System.Linq;
using DevExpress.XtraGrid;
using DevExpress.Xpf;
using DevExpress.Data;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections;
using System.Diagnostics;
using DevEx.Thanh.Class;

namespace DevEx
{
    public partial class ucPhieuXuat : DevExpress.XtraEditors.XtraUserControl
    {
        private String _NX = "X";
        private int _ID_DPNX;
        private int _ID_DonVi;
        //private int _ID_SanPham;
        //private int _ID_HopDong;
        private int _ID_User = GlobalVar.CurrentUser.ID_User;
        private int _ID_Kho = Convert.ToInt32(GlobalVar.CurrentUser.ID_Kho);
        private int _SoPhieu = 0;
        private String _ChuPhieu = "";

        CDPNX m_DPNX = new CDPNX();
        QLVTDataContext dc = new QLVTDataContext();
        DataTable dtSLNX;

        public ucPhieuXuat()
        {
            InitializeComponent();
            KhoiTaoDM();

            //So Phieu Moi            
            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetNewSoPhieu("X", DateTime.Now, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, ref _SoPhieu);


            //Ngay Phieu
            dtpNgayPhieu.EditValue = DateTime.Now;
            lueKho.EditValue = _ID_Kho;

            CUserController m_user = new CUserController();
            lblNguoiLapPhieu.Text = "Người lập phiếu: " + m_user.SelectRecordByID(_ID_User).FullName;

            KhoiTaodtSLNX();
            KhoiTaoSLNX(0);
            FormatdtgPhieuXuat();
            KhoiTaoGiaoDien(false);
            lueKho.Focus();
            btnThem_Click(null, null);
        }

        public ucPhieuXuat(int ID_DPNX)
        {
            InitializeComponent();
            _ID_DPNX = ID_DPNX;
            CDPNX m_DPNX = new CDPNX();
            _SoPhieu = Convert.ToInt32(m_DPNX.SelectRecordByID(ID_DPNX).SoPhieu);
            _ChuPhieu = Convert.ToString(m_DPNX.SelectRecordByID(ID_DPNX).ChuPhieu);
            KhoiTaoDM();

            KhoiTaodtSLNX();
            KhoiTaoDPNX();
            FormatdtgPhieuXuat();
            KhoiTaoGiaoDien(true);
        }

        public ucPhieuXuat(int ID_PhieuNhap, int Gido)
        {
            int Dodo = Gido; // hehe

            //Tạo Phiếu xuất lấy thông tin từ phiếu nhập       
            InitializeComponent();
            KhoiTaoDM();

            //So Phieu Moi            
            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetNewSoPhieu("X", DateTime.Now, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, ref _SoPhieu);


            //Ngay Phieu
            dtpNgayPhieu.EditValue = DateTime.Now;
            lueKho.EditValue = _ID_Kho;

            // Load mặc định thủ kho và trường phòng vật tư
            CThamSo m_ThamSo = new CThamSo();
            txtTPVatTu.EditValue = m_ThamSo.SelectRecordByID("TruongPhong").GiaTri_ThamSo;
            CKho m_Kho = new CKho();
            txtThuKho.EditValue = m_Kho.SelectRecordByID(_ID_Kho).ThuKho;

            CUserController m_user = new CUserController();
            lblNguoiLapPhieu.Text = "Người lập phiếu: " + m_user.SelectRecordByID(_ID_User).FullName;

            KhoiTaodtSLNX();

            KhoiTaoSLNX(ID_PhieuNhap);
            foreach(DataRow r in dtSLNX.Rows)
            {
                r["Status"] = 1;
            }
            
            // bổ sung status = 1                           
            FormatdtgPhieuXuat();
            KhoiTaoGiaoDien(false);
        }

        //public int GetSoPhieu()
        //{
        //    int q = 0;
        //    q = Convert.ToInt32((from p in dc.tblDPNXes
        //                         where p.NX == _NX && Convert.ToDateTime(p.NgayPhieu).Year == DateTime.Now.Year && Convert.ToDateTime(p.NgayPhieu).Month == DateTime.Now.Month
        //                         select p.SoPhieu).Max());

        //    return q + 1;
        //}

        public void KhoiTaoDPNX()
        {
            var DPNX = m_DPNX.SelectRecordByID(_ID_DPNX);
            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetSoPhieu(_ID_DPNX);

            dtpNgayPhieu.EditValue = DPNX.NgayPhieu;
            lueTCNX.EditValue = DPNX.ID_TCNX;
            lueKho.EditValue = DPNX.ID_Kho;
            txtLyDoNhap.EditValue = DPNX.LyDoNhapXuat;
            txtHoaDon.EditValue = DPNX.HoaDon;
            txtTPVatTu.EditValue = DPNX.TruongPhong;
            txtNguoiGiaoNhan.EditValue = DPNX.NguoiGiaoNhan;
            txtThuKho.EditValue = DPNX.ThuKho;

            CUserController m_user = new CUserController();
            lblNguoiLapPhieu.Text = "Người lập phiếu: " + m_user.SelectRecordByID(Convert.ToInt32(DPNX.ID_CreatedUser)).FullName;

            _ID_DonVi = Convert.ToInt32(DPNX.ID_DonVi);
            txtDonVi.EditValue = DPNX.tblDonVi.DonVi;
            txtDiaChi.EditValue = DPNX.tblDonVi.DiaChi;

            if (DPNX.ID_TCNX == 8) //Xuất sửa chữa
            {
                lueLoaiSanPham.Visible = true;
                lueSanPham.Visible = true;
                lblSanPham.Visible = true;
                lblLoaiSanPham.Visible = true;
                btnRefeshSanPham.Visible = true;
                
                CSanPham m_sanpham = new CSanPham();
                var sanpham = m_sanpham.SelectRecordByID(Convert.ToInt32(DPNX.ID_SanPham));
                lueLoaiSanPham.EditValue = sanpham.ID_Parent;
                lueSanPham.EditValue = DPNX.ID_SanPham;
            }

            if (DPNX.ID_TCNX == 7) //Xuất sản phẩm
            {
                lueLoaiSanPham.Visible = true;
                lueSanPham.Visible = false;
                lblSanPham.Visible = false;
                lblLoaiSanPham.Visible = true;
                btnRefeshSanPham.Visible = true;
                
                lueLoaiSanPham.EditValue = DPNX.ID_SanPham;                
            }
            KhoiTaoSLNX(DPNX.ID_DPNX);
        }

        public void CreatNewRowTon(int ID_MatHang, double SLKH)
        {
            gridView1.AddNewRow();

            int rowHandle = gridView1.GetRowHandle(gridView1.DataRowCount);
            if (gridView1.IsNewItemRow(rowHandle))
            {
                CTon m_ton = new CTon();
                tblTon obj_ton = m_ton.SelectRecordByID(ID_MatHang);

                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_MatHang"], ID_MatHang);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["VatTu"], obj_ton.tblVatTu.VatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_CCL"], obj_ton.ID_CCL);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_NguonVatTu"], obj_ton.ID_NguonVatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_HopDong"], obj_ton.ID_HopDong);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Gia"], obj_ton.Gia);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["SLKH"], SLKH);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["NamSX"], obj_ton.NamSX);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ThanhTien"], obj_ton.Gia * SLKH);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["MaKyHieu"], obj_ton.tblVatTu.MaKyHieu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["SoTheKho"], obj_ton.SoTheKho);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["TangKeKhoang"], obj_ton.TangKeKhoang);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Code"], obj_ton.Code);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["GhiChu"], "");
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Status"], 1);
                
                if (obj_ton.ID_HopDong == null)
                    gridView1.SetRowCellValue(rowHandle, gridView1.Columns["NguonGoc"], obj_ton.NguonGoc);
                else
                    gridView1.SetRowCellValue(rowHandle, gridView1.Columns["NguonGoc"], obj_ton.tblHopDong.SoHopDong);
                

                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Del"], false);

                gridView1.UpdateCurrentRow();
            }
        }

        public void KhoiTaodtSLNX()
        {
            dtSLNX = new DataTable();
            dtSLNX.Columns.Add("Del", typeof(Boolean));
            dtSLNX.Columns.Add("ID_SLNX", typeof(int));
            dtSLNX.Columns.Add("ID_MatHang", typeof(int));
            dtSLNX.Columns.Add("ID_VatTu", typeof(int));
            dtSLNX.Columns.Add("VatTu", typeof(String));
            dtSLNX.Columns.Add("MaKyHieu", typeof(String));
            dtSLNX.Columns.Add("NamSX", typeof(String));
            dtSLNX.Columns.Add("ID_CCL", typeof(int));
            dtSLNX.Columns.Add("Gia", typeof(Double));
            dtSLNX.Columns.Add("SLKH", typeof(Double));
            dtSLNX.Columns.Add("ThanhTien", typeof(Double));
            dtSLNX.Columns.Add("ID_NguonVatTu", typeof(int));
            dtSLNX.Columns.Add("ID_HopDong", typeof(int));
            dtSLNX.Columns.Add("NguonGoc", typeof(String));
            dtSLNX.Columns.Add("TangKeKhoang", typeof(String));
            dtSLNX.Columns.Add("GhiChu", typeof(String));
            dtSLNX.Columns.Add("SoTheKho", typeof(String));
            dtSLNX.Columns.Add("Code", typeof(String));
            dtSLNX.Columns.Add("Status", typeof(int));//0: binh thuong, 1: them, 2: sua, 3: xoa
        }

        public void KhoiTaoSLNX(int ID_DPNX)
        {
            //CSLNX m_SLNX = new CSLNX();
            //dtgPhieuNhap.DataSource = m_SLNX.SelectAllRecord(ID_DPNX);

            var q = from p in dc.tblSLNXes
                    where p.ID_DPNX == ID_DPNX
                    select new
                    {
                        p.ID_SLNX,
                        p.ID_MatHang,
                        p.tblTon.ID_VatTu,
                        p.tblTon.tblVatTu.VatTu,
                        p.tblTon.Code,
                        p.tblTon.tblVatTu.MaKyHieu,
                        p.tblTon.NamSX,
                        p.tblTon.ID_CCL,
                        p.tblTon.ID_NguonVatTu,
                        p.tblTon.ID_HopDong,
                        p.tblTon.Gia,
                        p.SLKH,
                        ThanhTien = p.SLKH * p.tblTon.Gia,
                        p.tblTon.SoTheKho,
                        p.tblTon.TangKeKhoang,
                        p.tblTon.tblHopDong.SoHopDong,
                        p.GhiChu
                    };

            dtSLNX.Clear();

            foreach (var ton in q)
            {
                DataRow row = dtSLNX.NewRow();
                row["ID_SLNX"] = ton.ID_SLNX;
                row["ID_MatHang"] = ton.ID_MatHang;
                row["ID_VatTu"] = ton.ID_VatTu;
                row["VatTu"] = ton.VatTu;
                row["Code"] = ton.Code;
                row["MaKyHieu"] = ton.MaKyHieu;
                row["ID_CCL"] = ton.ID_CCL;
                row["Gia"] = ton.Gia;
                row["NamSX"] = ton.NamSX ?? "00/0000";
                row["SLKH"] = ton.SLKH ?? 0;
                row["ThanhTien"] = ton.ThanhTien;
                row["ID_NguonVatTu"] = ton.ID_NguonVatTu;

                if (ton.ID_HopDong == null)
                    row["ID_HopDong"] = DBNull.Value;
                else
                    row["ID_HopDong"] = ton.ID_HopDong;

                row["SoTheKho"] = ton.SoTheKho;
                row["TangKeKhoang"] = ton.TangKeKhoang;
                row["GhiChu"] = ton.GhiChu;
                row["NguonGoc"] = ton.SoHopDong;
                row["Status"] = 0;//binh thuong
                row["Del"] = 0;//binh thuong
                dtSLNX.Rows.Add(row);
            }

            dtgPhieuXuat.DataSource = dtSLNX;
        }

        public void FormatdtgPhieuXuat()
        {
            gridView1.OptionsView.ShowFooter = true;
            gridView1.Columns.ColumnByFieldName("ID_SLNX").Visible = false;
            gridView1.Columns.ColumnByFieldName("ID_VatTu").Visible = false;
            gridView1.Columns.ColumnByFieldName("ID_MatHang").Visible = false;
            gridView1.Columns.ColumnByFieldName("Status").Visible = false;
            //gridView1.Columns.ColumnByFieldName("Code").Visible = false;
            gridView1.Columns.ColumnByFieldName("ID_HopDong").Visible = false;

            //Columns Code
            var cl_Code = gridView1.Columns.ColumnByFieldName("Code");
            cl_Code.Width = 30;
            cl_Code.Caption = "Code";
            cl_Code.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Code.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Del
            var cl_Del = gridView1.Columns.ColumnByFieldName("Del");
            cl_Del.Width = 30;
            cl_Del.Caption = "Xóa";
            cl_Del.OptionsColumn.AllowEdit = false;
            cl_Del.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Del.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns VatTu
            var cl_VatTu = gridView1.Columns.ColumnByFieldName("VatTu");
            cl_VatTu.Width = 150;
            cl_VatTu.Caption = "Vật Tư";
            cl_VatTu.OptionsColumn.AllowEdit = false;
            cl_VatTu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_VatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns CCL
            var cl_CCL = gridView1.Columns.ColumnByFieldName("ID_CCL");
            cl_CCL.Width = 50;
            cl_CCL.Caption = "CCL";
            cl_CCL.OptionsColumn.AllowEdit = false;
            cl_CCL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_CCL.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Nguon Tai Chinh
            var cl_NguonVatTu = gridView1.Columns.ColumnByFieldName("ID_NguonVatTu");
            cl_NguonVatTu.Width = 80;
            cl_NguonVatTu.Caption = "N. TC";
            cl_NguonVatTu.OptionsColumn.AllowEdit = false;
            cl_NguonVatTu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NguonVatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Nguon Nhap
            var cl_NguonNhap = gridView1.Columns.ColumnByFieldName("ID_HopDong");
            cl_NguonNhap.Width = 80;
            cl_NguonNhap.Caption = "N. Nhập";
            cl_NguonNhap.OptionsColumn.AllowEdit = false;
            cl_NguonNhap.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NguonNhap.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Nguon Goc
            var cl_NguonGoc = gridView1.Columns.ColumnByFieldName("NguonGoc");
            cl_NguonGoc.Width = 80;
            cl_NguonGoc.Caption = "Nguồn Gốc";
            cl_NguonGoc.OptionsColumn.AllowEdit = false;
            cl_NguonGoc.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_NguonGoc.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //format Nguon Tai Chinh
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit_NguonVatTu = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            CNguonVatTu m_nvt = new CNguonVatTu();
            repositoryItemLookUpEdit_NguonVatTu.DataSource = m_nvt.SelectAllRecord();

            repositoryItemLookUpEdit_NguonVatTu.DisplayMember = "NguonVatTu";
            repositoryItemLookUpEdit_NguonVatTu.ValueMember = "ID_NguonVatTu";
            repositoryItemLookUpEdit_NguonVatTu.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo("NguonVatTu", "NguonVatTu", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
            //repositoryItemLookUpEdit_NguonVatTu.Appearance.Font = new Font(this.Appearance.Font.Name, 10);
            cl_NguonVatTu.ColumnEdit = repositoryItemLookUpEdit_NguonVatTu;

            ////format Nguon Nhap
            //DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit_NguonNhap = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            //CHopDong m_HopDong = new CHopDong();
            //repositoryItemLookUpEdit_NguonNhap.DataSource = m_nvt.SelectAllRecord();

            //repositoryItemLookUpEdit_NguonNhap.DisplayMember = "SoHopDong";
            //repositoryItemLookUpEdit_NguonNhap.ValueMember = "ID_HopDong";
            //repositoryItemLookUpEdit_NguonNhap.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            //new DevExpress.XtraEditors.Controls.LookUpColumnInfo("SoHopDong", "SoHopDong", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
            ////repositoryItemLookUpEdit_NguonVatTu.Appearance.Font = new Font(this.Appearance.Font.Name, 10);
            //cl_NguonNhap.ColumnEdit = repositoryItemLookUpEdit_NguonNhap;

            //Columns NamSX
            var cl_NamSX = gridView1.Columns.ColumnByFieldName("NamSX");
            cl_NamSX.Width = 50;
            cl_NamSX.OptionsColumn.AllowEdit = false;
            cl_NamSX.Caption = "Năm SX";
            cl_NamSX.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NamSX.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns MaKyHieu
            var cl_MaKyHieu = gridView1.Columns.ColumnByFieldName("MaKyHieu");
            cl_MaKyHieu.Caption = "Mã Hiệu";
            cl_MaKyHieu.Width = 100;
            cl_MaKyHieu.OptionsColumn.AllowEdit = false;
            cl_MaKyHieu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_MaKyHieu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns SoTheKho
            var cl_SoTheKho = gridView1.Columns.ColumnByFieldName("SoTheKho");
            cl_SoTheKho.Width = 60;
            cl_SoTheKho.OptionsColumn.AllowEdit = false;
            cl_SoTheKho.Caption = "Thẻ Kho";
            cl_SoTheKho.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SoTheKho.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns TangKeKhoang
            var cl_TangKeKhoang = gridView1.Columns.ColumnByFieldName("TangKeKhoang");
            cl_TangKeKhoang.Width = 40;
            cl_TangKeKhoang.OptionsColumn.AllowEdit = false;
            cl_TangKeKhoang.Caption = "Vị trí";
            cl_TangKeKhoang.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_TangKeKhoang.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns GhiChu
            var cl_GhiChu = gridView1.Columns.ColumnByFieldName("GhiChu");
            cl_GhiChu.Caption = "Ghi chú";
            cl_GhiChu.AppearanceCell.BackColor = Color.Azure;
            cl_GhiChu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_GhiChu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;


            //Columns Gia
            var cl_Gia = gridView1.Columns.ColumnByFieldName("Gia");
            cl_Gia.Width = 70;
            cl_Gia.Caption = "Đơn giá";
            cl_Gia.OptionsColumn.AllowEdit = false;
            cl_Gia.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_Gia.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Gia.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_Gia.DisplayFormat.FormatString = "n0";

            //Columns ThanhTien           
            var cl_ThanhTien = gridView1.Columns["ThanhTien"];
            cl_ThanhTien.Width = 80;
            cl_ThanhTien.OptionsColumn.AllowEdit = false;
            cl_ThanhTien.Caption = "Thành tiền";
            cl_ThanhTien.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "ThanhTien", "{0:n0}");
            cl_ThanhTien.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_ThanhTien.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_ThanhTien.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_ThanhTien.DisplayFormat.FormatString = "#,###.#";


            //Columns SLTonKH
            var cl_SLTonKH = gridView1.Columns.ColumnByFieldName("SLKH");
            cl_SLTonKH.Width = 60;
            cl_SLTonKH.AppearanceCell.BackColor = Color.Azure;
            cl_SLTonKH.Caption = "SLKH";
            cl_SLTonKH.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_SLTonKH.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SLTonKH.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_SLTonKH.DisplayFormat.FormatString = "#,###.#";

            //repositoryItemLookUpEdit1.AutoHeight = false;
            //repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            //new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            //repositoryItemLookUpEdit1.DropDownRows = 10;
            //repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1";
            //repositoryItemLookUpEdit1.PopupWidth = 220;

            //format CCL
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit_CCL = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            CCCL m_ccl = new CCCL();
            repositoryItemLookUpEdit_CCL.DataSource = m_ccl.SelectAllRecord();

            repositoryItemLookUpEdit_CCL.DisplayMember = "CCL";
            repositoryItemLookUpEdit_CCL.ValueMember = "ID_CCL";
            repositoryItemLookUpEdit_CCL.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CCL", "CCL", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
            ((DevExpress.XtraGrid.Views.Base.ColumnView)dtgPhieuXuat.MainView).Columns["ID_CCL"].ColumnEdit = repositoryItemLookUpEdit_CCL;
        }

        private void ucPhieuXuat_Load(object sender, EventArgs e)
        {
            //gridView1.OptionsBehavior.Editable = false;
            KhoiTaoAutoCompleteDonVi();
            pnlSoPhieu.Visible = false;
        }

        public void KhoiTaoDM()
        {
            //1. Danh muc Tinh chat Nhap
            CTCNX m_TCNX = new CTCNX();
            lueTCNX.Properties.DisplayMember = "TCNX";
            lueTCNX.Properties.ValueMember = "ID_TCNX";
            lueTCNX.Properties.DataSource = m_TCNX.SelectAllRecord(false);


            //2. Danh muc Kho
            CKho m_kho = new CKho();
            IQueryable<tblKho> list = m_kho.SelectAllRecord();

            lueKho.Properties.DisplayMember = "Kho";
            lueKho.Properties.ValueMember = "ID_Kho";

            lueKho.Properties.DataSource = list;
            lueKho.Properties.PopulateColumns();

            //4. Danh muc LoaiSanPham
            var LSP = from p in dc.tblSanPhams
                      where p.ID_Parent == null
                      select new {p.ID_SanPham, p.SanPham};

            lueLoaiSanPham.Properties.DataSource = LSP;
            lueLoaiSanPham.Properties.DisplayMember = "SanPham";
            lueLoaiSanPham.Properties.ValueMember = "ID_SanPham";
        }

        #region Thêm, Xóa, Sửa
        private void btnThem_Click(object sender, EventArgs e)
        {
            lueTCNX.Focus();
            KhoiTaoGiaoDien(false);
            Clear();
            // Load mặc định thủ kho và trường phòng vật tư
            CThamSo m_ThamSo = new CThamSo();
            txtTPVatTu.EditValue = m_ThamSo.SelectRecordByID("TruongPhong").GiaTri_ThamSo;
            CKho m_Kho = new CKho();
            txtThuKho.EditValue = m_Kho.SelectRecordByID(_ID_Kho).ThuKho;
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            KhoiTaoGiaoDien(false);
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {

            var DPNX = m_DPNX.SelectRecordByID(_ID_DPNX);

            // Kiểm tra phiếu đã được xác nhận chưa
            if (DPNX.ID_ApproveUser != null)
            {
                MessageBox.Show("Phiếu đã được xác nhận, hủy xác nhận trước khi xóa");
                return;
            }

            //Kiểm tra người lập phiếu
            if (DPNX.ID_CreatedUser == _ID_User)
            {
                String SoPhieu = txtSoPhieu.Text;
                DialogResult dialogResult = MessageBox.Show("Bạn muốn xóa phiếu số: " + SoPhieu, "Chú ý", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    //Xoa phieu
                    m_DPNX.Delete(_ID_DPNX);

                    //Refesh phiếu
                    lueTCNX.Focus();
                    KhoiTaoGiaoDien(false);
                    Clear();
                }

            }
            else
                MessageBox.Show("Bạn không phải người lập phiếu");               
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            //1.  Kiểm tra dữ liệu
            //1.1 Kiểm tra chọn Kho
            if (lueKho.EditValue == null)
            {
                MessageBox.Show("Bạn chưa chọn Kho");
                lueKho.Focus();
                return;
            }
            //1.2 Kiểm tra chọn TCNX và Sản phẩm
            if (lueTCNX.EditValue == null)
            {
                MessageBox.Show("Bạn chưa chọn Tính chất xuất");
                lueTCNX.Focus();
                return;
            }
            else
            {
                if (lueTCNX.Text == "Xuất sửa chữa")
                {
                    if (lueSanPham.EditValue == null)
                    {
                        MessageBox.Show("Bạn chưa chọn Sản phẩm để xuất sửa chữa");
                        lueSanPham.Focus();
                        return;
                    }
                }
                if (lueTCNX.Text == "Xuất sản phẩm")
                {
                    if (lueLoaiSanPham.EditValue == null)
                    {
                        MessageBox.Show("Bạn chưa chọn đầu việc để xuất sản phẩm");
                        lueLoaiSanPham.Focus();
                        return;
                    }
                }

            }
            //1.3 Kiểm tra DVGN
            if (_ID_DonVi == 0)
            {
                MessageBox.Show("Bạn chưa chọn Đơn vị nhận hàng");
                txtDonVi.Focus();
                return;
            }


            // Tính tổng giá trị phiếu xuất
            Double TongGiaTri = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                int status = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["Status"]));
                if (status != 3)
                {
                    Double Gia = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]));
                    Double SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    TongGiaTri += Gia * SLKH;
                }
            }
            //2. DPNX
            tblDPNX obj_DPNX = new tblDPNX();
            CDPNX m_DPNX = new CDPNX();
            if (_ID_DPNX == 0)
            {
                //var obj_DPNX = m_DPNX.SelectRecordByID(_ID_DPNX);

                obj_DPNX.HoaDon = Convert.ToString(txtHoaDon.EditValue ?? "");
                obj_DPNX.NX = _NX;
                obj_DPNX.LyDoNhapXuat = Convert.ToString(txtLyDoNhap.EditValue ?? "");
                obj_DPNX.NguoiGiaoNhan = Convert.ToString(txtNguoiGiaoNhan.EditValue ?? "");
                obj_DPNX.TruongPhong = Convert.ToString(txtTPVatTu.EditValue ?? "");
                obj_DPNX.ThuKho = Convert.ToString(txtThuKho.EditValue ?? "");
                obj_DPNX.NgayPhieu = Convert.ToDateTime(dtpNgayPhieu.EditValue);
                obj_DPNX.ID_Kho = Convert.ToInt32(lueKho.EditValue);
                obj_DPNX.ID_TCNX = Convert.ToInt32(lueTCNX.EditValue);
                obj_DPNX.ID_CreatedUser = _ID_User;
                obj_DPNX.SoPhieu = _SoPhieu;
                obj_DPNX.ChuPhieu = _ChuPhieu;

                if (Convert.ToInt32(lueTCNX.EditValue) == 7) //xuất sản phẩm
                {
                    obj_DPNX.ID_SanPham = Convert.ToInt32(lueLoaiSanPham.EditValue);
                }

                if (Convert.ToInt32(lueTCNX.EditValue) == 8) //xuất sửa chữa
                {
                    obj_DPNX.ID_SanPham = Convert.ToInt32(lueSanPham.EditValue);
                }

                //if (lueSanPham.EditValue == null)
                //    obj_DPNX.ID_SanPham = Convert.ToInt32(lueLoaiSanPham.EditValue);
                //else
                //    obj_DPNX.ID_SanPham = Convert.ToInt32(lueSanPham.EditValue);

                obj_DPNX.ID_DonVi = _ID_DonVi;
                obj_DPNX.TongGiaTri = TongGiaTri;

                CKho m_kho = new CKho();
                obj_DPNX.DuoiPhieu = m_kho.SelectRecordByID(_ID_Kho).KH_Kho;

                _ID_DPNX = m_DPNX.Insert(obj_DPNX);
            }
            else
            {
                obj_DPNX.ID_DPNX = _ID_DPNX;
                obj_DPNX.HoaDon = Convert.ToString(txtHoaDon.EditValue ?? "");
                obj_DPNX.NX = _NX;
                obj_DPNX.LyDoNhapXuat = Convert.ToString(txtLyDoNhap.EditValue ?? "");
                obj_DPNX.NguoiGiaoNhan = Convert.ToString(txtNguoiGiaoNhan.EditValue ?? "");
                obj_DPNX.TruongPhong = Convert.ToString(txtTPVatTu.EditValue ?? "");
                obj_DPNX.ThuKho = Convert.ToString(txtThuKho.EditValue ?? "");
                obj_DPNX.NgayPhieu = Convert.ToDateTime(dtpNgayPhieu.EditValue);
                obj_DPNX.ID_Kho = Convert.ToInt32(lueKho.EditValue);
                obj_DPNX.ID_TCNX = Convert.ToInt32(lueTCNX.EditValue);
                obj_DPNX.ID_CreatedUser = _ID_User;
                obj_DPNX.SoPhieu = _SoPhieu;
                obj_DPNX.ChuPhieu = _ChuPhieu;

                CDPNX m_dpnx = new CDPNX();
                obj_DPNX.ID_ApproveUser = m_dpnx.SelectRecordByID(_ID_DPNX).ID_ApproveUser;

                if (Convert.ToInt32(lueTCNX.EditValue) == 7) //xuất sản phẩm
                {
                    obj_DPNX.ID_SanPham = Convert.ToInt32(lueLoaiSanPham.EditValue);
                }

                if (Convert.ToInt32(lueTCNX.EditValue) == 8) //xuất sửa chữa
                {
                    obj_DPNX.ID_SanPham = Convert.ToInt32(lueSanPham.EditValue);
                }

                obj_DPNX.ID_DonVi = _ID_DonVi;
                obj_DPNX.TongGiaTri = TongGiaTri;

                CKho m_kho = new CKho();
                obj_DPNX.DuoiPhieu = m_kho.SelectRecordByID(_ID_Kho).KH_Kho;

                m_DPNX.Update(obj_DPNX);
            }



            // 3. Chi Tiet Nhap Xuat (SLNX)
            // 3.1 Get ID_MatHang 
            // 3.1.1 Nếu tồn tại ID_MatHang trong tồn
            // 3.1.2 Ngược lại không có trong tồn -> tạo tồn trước
            // 3.2 Update SLNX và tồn

            CTon m_ton = new CTon();
            CSLNX m_SLNX = new CSLNX();

            for (int i = 0; i < gridView1.RowCount; i++)
            {

                int ID_MatHang = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_MatHang"]));
                double Gia = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]));

                int status = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["Status"]));
                if (status == 1)
                { //Thêm

                    double SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    m_ton.InsertXuat(ID_MatHang, SLKH);

                    tblSLNX objSLNX = new tblSLNX();
                    objSLNX.ID_MatHang = ID_MatHang;
                    objSLNX.ID_DPNX = obj_DPNX.ID_DPNX;
                    objSLNX.SLKH = SLKH;
                    objSLNX.ThanhTien = SLKH * Gia;
                    objSLNX.GhiChu = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["GhiChu"]) ?? "");

                    m_SLNX.Insert(objSLNX);
                }


                //Xóa
                if (status == 3)
                {
                    int ID_SLNX = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_SLNX"]));
                    double SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));

                    //1. Xóa SLNX
                    m_SLNX.Delete(ID_SLNX);

                    //2. Xóa trong Tồn (SLTonKH = SLTonKH + SLKH)
                    m_ton.DeleteXuat(ID_MatHang, SLKH);

                }
                //Sửa
                if (status == 2)
                {
                    int ID_SLNX = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_SLNX"]));
                    tblSLNX objSLNX = m_SLNX.SelectRecordByID(ID_SLNX);
                    double SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    //Update tblTon voi SLKH_Old, SLKH_New
                    m_ton.UpdateXuat(ID_MatHang, Convert.ToDouble(objSLNX.SLKH), SLKH);

                    tblSLNX _SLNX = new tblSLNX();
                    _SLNX.ID_SLNX = ID_SLNX;
                    _SLNX.ID_MatHang = ID_MatHang;
                    _SLNX.ID_DPNX = _ID_DPNX;
                    _SLNX.SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    _SLNX.GhiChu = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["GhiChu"]) ?? "");
                    _SLNX.ThanhTien = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["ThanhTien"]));
                    m_SLNX.Update(_SLNX);
                }
            }
            KhoiTaoSLNX(obj_DPNX.ID_DPNX);
            KhoiTaoGiaoDien(true);
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            if (_ID_DPNX != 0)
            {
                KhoiTaoDPNX();
                KhoiTaoGiaoDien(true);
            }
            else
            {
                lueTCNX.Focus();
                KhoiTaoGiaoDien(false);
                Clear();
            }
        }

        public void KhoiTaoGiaoDien(Boolean f)
        {
            txtSoPhieu.Properties.ReadOnly = true;
            txtDiaChi.Properties.ReadOnly = true;
            lueKho.Enabled = false;

            txtDonVi.Properties.ReadOnly = f;
            txtHoaDon.Properties.ReadOnly = f;
            txtNguoiGiaoNhan.Properties.ReadOnly = f;
            txtTPVatTu.Properties.ReadOnly = f;
            txtThuKho.Properties.ReadOnly = f;
            txtLyDoNhap.Properties.ReadOnly = f;


            lueLoaiSanPham.Enabled = !f;
            lueSanPham.Enabled = !f;

            lueTCNX.Properties.ReadOnly = f;
            dtpNgayPhieu.Properties.ReadOnly = f;

            for (int i = 0; i < gridView1.Columns.Count; i++)
                gridView1.Columns[i].OptionsColumn.AllowEdit = false;


            gridView1.Columns["Del"].OptionsColumn.AllowEdit = !f;
            gridView1.Columns["GhiChu"].OptionsColumn.AllowEdit = !f;

            btnThem.Enabled = f;
            btnSua.Enabled = f;
            btnXoa.Enabled = f;
            btnGhi.Enabled = !f;
            btnHuy.Enabled = !f;
        }

        public void Clear()
        {
            //So Phieu Moi
            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetNewSoPhieu("X", DateTime.Now, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, ref _SoPhieu);

            //Ngay Phieu
            dtpNgayPhieu.EditValue = DateTime.Now;

            txtDonVi.EditValue = "";
            txtHoaDon.EditValue = "";
            lueKho.EditValue = _ID_Kho;

            lueLoaiSanPham.EditValue = null;
            lueSanPham.EditValue = null;
            lueTCNX.EditValue = null;
            txtLyDoNhap.EditValue = "";
            txtDiaChi.Text = "";

            dtSLNX.Rows.Clear();
            _ID_DPNX = 0;
            _ID_DonVi = 0;
        }
        #endregion


        private void dtgPhieuXuat_DoubleClick(object sender, EventArgs e)
        {
            if (btnGhi.Enabled)
            {
                int ID_Kho = 0;
                try { ID_Kho = Convert.ToInt32(lueKho.EditValue); }
                catch { }
                if (ID_Kho == 0)
                {
                    MessageBox.Show("Bạn chưa chọn Kho cần làm phiếu xuất");
                    lueKho.Focus();
                    return;
                }
                XtraForm frmTon = new frmHangTon(ID_Kho, this);
                frmTon.ShowDialog();
            }
        }

        #region AutoComplete DonVi
        AutoCompleteStringCollection donviSource = new AutoCompleteStringCollection();

        public void KhoiTaoAutoCompleteDonVi()
        {
            var listDonVi = from p in dc.tblDonVis
                            where p.Cuoi == true && !(from q in dc.tblKhos select q.ID_DonVi).Contains(p.ID_DonVi)
                            orderby p.DonVi
                            select p;

            foreach (tblDonVi donvi in listDonVi)
                donviSource.Add(donvi.DonVi);

            txtDonVi.MaskBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtDonVi.MaskBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            txtDonVi.MaskBox.AutoCompleteCustomSource = donviSource;
        }

        private void txtDonVi_Enter(object sender, EventArgs e)
        {
            KhoiTaoAutoCompleteDonVi();
        }

        private void txtDonVi_Leave(object sender, EventArgs e)
        {
            CDonVi m_donvi = new CDonVi();
            tblDonVi objDonVi = m_donvi.SelectRecordByName(Convert.ToString(txtDonVi.EditValue));
            if (objDonVi == null)
            {
                txtDonVi.Text = "";
                txtDiaChi.Text = "";
                _ID_DonVi = 0;
                //var frm = new frmMain();
                //frm.AddTab("Danh mục Đơn vị", new ucDonVi());
            }
            else
            {
                _ID_DonVi = objDonVi.ID_DonVi;
                txtDonVi.EditValue = objDonVi.DonVi;
                txtDiaChi.EditValue = objDonVi.DiaChi;
            }
        }

        private void txtDonVi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                txtDiaChi.Focus();
        }

        #endregion

        private void lueLoaiSanPham_EditValueChanged(object sender, EventArgs e)
        {
            int ID_LoaiSP = Convert.ToInt32(lueLoaiSanPham.EditValue);
            KhoiTaoDMSanPham(ID_LoaiSP);
        }

        public void KhoiTaoDMSanPham(int ID_LoaiSP)
        {
            //3. Danh muc SanPham
            var q = from p in dc.tblSanPhams
                    where p.ID_Parent == ID_LoaiSP
                    select new { p.ID_SanPham, p.SanPham };

            lueSanPham.Properties.DataSource = q;
            lueSanPham.Properties.DisplayMember = "SanPham";
            lueSanPham.Properties.ValueMember = "ID_SanPham";
        }


        private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                int Status = Convert.ToInt32(gridView1.GetRowCellValue(e.RowHandle, gridView1.Columns["Status"]));
                if (Status == 1)//add new
                {
                    //e.Appearance.BackColor = Color.Blue;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                }
                if (Status == 2)//update row
                {
                    //e.Appearance.BackColor = Color.MediumSpringGreen;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.ForeColor = Color.Blue;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Italic);
                }
                if (Status == 3)//delete row
                {
                    //e.Appearance.BackColor = Color.Yellow;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.ForeColor = Color.Red;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                }
            }
        }


        #region Delete Selection LookUpEdit LoaiSanPham, SanPham
        private void lueLoaiSanPham_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                lueLoaiSanPham.ClosePopup();
                lueLoaiSanPham.EditValue = null;
                lueSanPham.ClosePopup();
                lueSanPham.EditValue = null;
                e.Handled = true;
            }
        }

        private void lueSanPham_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                lueSanPham.ClosePopup();
                lueSanPham.EditValue = null;
                lueLoaiSanPham.ClosePopup();
                lueLoaiSanPham.EditValue = null;
                e.Handled = true;
            }
        }
        #endregion

        private void btnExcel_Click(object sender, EventArgs e)
        {
            CModule_Sy sy = new CModule_Sy();
            sy.ToExcel_PhieuXuat(_ID_DPNX);
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName != "Status")
            {
                try
                {
                    if (Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"])) != 1)
                        gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 2);
                }
                catch { }// bo qua loi them moi
            }

            if (e.Column.FieldName == "Del")
            {
                try
                {
                    Boolean Del = Convert.ToBoolean(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Del"]));
                    int Status = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"]));
                    if (Del == true)
                    {
                        if (Status == 1)
                            gridView1.DeleteRow(gridView1.FocusedRowHandle);
                        else
                            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 3);

                        gridView1.UpdateCurrentRow();
                    }
                    else
                    {
                        if (Status != 1)
                            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 2);
                        gridView1.UpdateCurrentRow();
                    }
                }
                catch { }
            }
        }

        private void lueTCNX_EditValueChanged(object sender, EventArgs e)
        {
            int ID_TCNX = Convert.ToInt32(lueTCNX.EditValue);
            String TCNX = lueTCNX.Text;
            if (TCNX != "Xuất sửa chữa")
            {
                lueLoaiSanPham.ClosePopup();
                lueLoaiSanPham.EditValue = null;
                lueSanPham.ClosePopup();
                lueSanPham.EditValue = null;
                lueSanPham.Visible = false;
                //lueLoaiSanPham.Visible = false;
                lblSanPham.Visible = false;
                //lblLoaiSanPham.Visible = false;
                //btnRefeshSanPham.Visible = false;
            }
            else
            {
                lueSanPham.Visible = true;
                lueLoaiSanPham.Visible = true;
                lblSanPham.Visible = true;
                lblLoaiSanPham.Visible = true;
                btnRefeshSanPham.Visible = true;
            }
        }

        private void btnDeleteRow_Click(object sender, EventArgs e)
        {
            if (!btnGhi.Enabled)
                return;

            try
            {
                if (Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"])) != 1)
                {
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 3);
                    gridView1.UpdateCurrentRow();
                }
            }
            catch { }// bo qua loi them moi
        }

        private void gridView1_HiddenEditor(object sender, EventArgs e)
        {
            //Kiểm tra Số lượng xuất


            //GridView View = sender as GridView;
            //if (View.FocusedColumn.Caption  == "SLKH")
            //{
            //    //Kiểm tra giá trị SLKH > SLTonKH hay SLTonTH hay khong
            //    int ID_MatHang = Convert.ToInt32(View.GetFocusedRowCellValue("ID_MatHang"));

            //    CTon m_ton = new CTon();
            //    tblTon obj_ton = m_ton.SelectRecordByID(ID_MatHang);

            //    Double SLKH = Convert.ToDouble(View.GetFocusedRowCellValue("SLKH"));

            //    if (SLKH > obj_ton.SLTonKH || SLKH > obj_ton.SLTonTH)
            //    {
            //        MessageBox.Show("SLKH phải nhỏ hơn SLTonKH và SLTonTH");
            //    }

            //}

            //if (View.FocusedRowHandle == View.RowCount - 1)
            //    View.FocusedRowHandle = 0;
            //else
            //    View.FocusedRowHandle++;
            //View.ShowEditor();
        }

        private void lueTCNX_VisibleChanged(object sender, EventArgs e)
        {

            lueTCNX.Properties.PopulateColumns();
            lueTCNX.Properties.Columns["ID_TCNX"].Visible = false;
            lueTCNX.Properties.Columns["IsNhap"].Visible = false;
        }

        private void lueLoaiSanPham_VisibleChanged(object sender, EventArgs e)
        {
            lueLoaiSanPham.Properties.PopulateColumns();
            try { lueLoaiSanPham.Properties.Columns["ID_SanPham"].Visible = false; }
            catch { };

        }

        private void lueSanPham_VisibleChanged(object sender, EventArgs e)
        {
            int ID_LSP = 0;
            if (lueLoaiSanPham.EditValue != null)
                ID_LSP = Convert.ToInt32(lueLoaiSanPham.EditValue);


            var q = from p in dc.tblSanPhams
                    where p.ID_Parent == ID_LSP
                    select new { p.ID_SanPham, p.SanPham };

            lueSanPham.Properties.DataSource = q;
            lueSanPham.Properties.DisplayMember = "SanPham";
            lueSanPham.Properties.ValueMember = "ID_SanPham";
            lueSanPham.Properties.PopulateColumns();
            try { lueSanPham.Properties.Columns["ID_SanPham"].Visible = false; }
            catch { };


        }

        private void btIn_Click(object sender, EventArgs e)
        {
            if (_ID_DPNX > 0)
            {
                //lấy dữ liệu đổ ra dataset
                DataTable dt = new DataTable();
                DevEx.Thanh.Utilities.XL_DULIEU.LayDuLieuRaBang("select * from fc_T_LayCTPhieu(" + _ID_DPNX + ")", ref dt);
                dt.TableName = "fc_T_LayCTPhieu";
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                //in báo cáo
                rptPhieuXuat rpt = new rptPhieuXuat();
                rpt.DataSource = ds;
                //set gia tri cho no
                rpt.Parameters["SoPhieu"].Value = txtSoPhieu.Text;
                //rpt.Parameters["NguoiNhan"].Value = txtNguoiGiaoNhan.Text;
                rpt.Parameters["Kho"].Value = lueKho.Text;
                rpt.Parameters["NgayPhieu"].Value = "Ngày: " + Convert.ToDateTime(dtpNgayPhieu.EditValue).ToString("dd/MM/yyyy");
                rpt.Parameters["MucDich"].Value = txtLyDoNhap.Text;
                if (lueSanPham.EditValue != null)
                    rpt.Parameters["SanPham"].Value = lueSanPham.Text;
                else
                {
                    rpt.Parameters["SanPham"].Value = "";
                }
                rpt.Parameters["SoPhuongAn"].Value = txtHoaDon.Text;
                double tongTien = (double)dt.Compute("sum(ThanhTien)", "");
                string tienChu = CThanh_Utilities.DocSo(tongTien).Trim(); rpt.Parameters["TienChu"].Value = tienChu;
                frmInPhieuOption frm = new frmInPhieuOption(false, rpt, txtNguoiGiaoNhan.Text);
                frm.ShowDialog();
                //rpt.RequestParameters = false;//bắt buộc hiển thị lên luôn, không chờ nhập parametter
                ////gán vào form
                ////frmReportViewer frm = new frmReportViewer(rpt);
                ////frm.ShowDialog();
                //ReportPrintTool pt = new ReportPrintTool(rpt);
                //pt.AutoShowParametersPanel = false; //giấu phần hiển thị cho nhập parametter
                //pt.ShowPreviewDialog();
            }
        }

        private void btnRefeshSanPham_Click(object sender, EventArgs e)
        {
            //CLoaiSanPham m_loaisanpham = new CLoaiSanPham();
            var LSP = from p in dc.tblSanPhams
                      where p.ID_Parent == null
                      select new { p.ID_SanPham, p.SanPham };

            lueLoaiSanPham.Properties.DataSource = LSP;
        }

        private void dtpNgayPhieu_DateTimeChanged(object sender, EventArgs e)
        {
            if (_ID_DPNX ==0)
            {
                //So Phieu Moi            
                CKho m_kho = new CKho();
                CModule_Sy module = new CModule_Sy();
                txtSoPhieu.EditValue = module.GetNewSoPhieu("X", dtpNgayPhieu.DateTime.Date, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, ref _SoPhieu);
            }
            
        }

        private void lblSoPhieu_DoubleClick(object sender, EventArgs e)
        {
            if (!btnSua.Enabled)
            {
                pnlSoPhieu.Visible = true;
                txtSo.EditValue = _SoPhieu;
                txtChuPhieu.EditValue = _ChuPhieu;
            }            
        }

        private void btnSoPhieu_Click(object sender, EventArgs e)
        {
            pnlSoPhieu.Visible = false;
            try
            {
                _SoPhieu = Convert.ToInt32(txtSo.EditValue);
                _ChuPhieu = Convert.ToString(txtChuPhieu.EditValue);
                CKho m_kho = new CKho();
                CModule_Sy module = new CModule_Sy();
                txtSoPhieu.EditValue = GetSoPhieu("X", dtpNgayPhieu.DateTime.Date, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, Convert.ToInt32(txtSo.EditValue), txtChuPhieu.Text);
            }
            catch { MessageBox.Show("Bạn nhập số phiếu chưa đúng."); };
        }

        public String GetSoPhieu(String NX, DateTime d, String DuoiPhieu, int SoPhieu, String ChuPhieu)
        {
            int q = 0;
            QLVTDataContext dc = new QLVTDataContext();
            // kiem tra ton tai so phieu
            q = Convert.ToInt32((from p in dc.tblDPNXes
                                 where p.NX == NX
                                 && Convert.ToDateTime(p.NgayPhieu).Year == d.Year && Convert.ToDateTime(p.NgayPhieu).Month == d.Month
                                 && p.DuoiPhieu == DuoiPhieu && p.SoPhieu == SoPhieu && p.ChuPhieu == ChuPhieu
                                 select p).Count());

            if (q > 0)
            {
                MessageBox.Show("Đã tồn tại số phiếu này");
                return "";
            }
            _SoPhieu = SoPhieu;
            _ChuPhieu = ChuPhieu;


            String DauPhieu = "";
            if (SoPhieu < 10)
                DauPhieu = "0" + SoPhieu.ToString() + ChuPhieu + DuoiPhieu;
            else
                DauPhieu = SoPhieu.ToString() + ChuPhieu + DuoiPhieu;

            String ThangNam = "";
            if (d.Month.ToString().Length == 1)
                ThangNam = "0" + d.Month.ToString() + "-" + d.Year.ToString().Substring(2, 2);
            else
                ThangNam = d.Month.ToString() + "-" + d.Year.ToString().Substring(2, 2);

            return DauPhieu + "/" + ThangNam;
        }
    }
}
